
package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Observer;

import javax.swing.JOptionPane;

import model.BuyPhotoOrSampleModel;
import model.FinanceSystemModel;
import model.SearchPhotoModel;
import model.SearchResultModel;
import model.UserPermissions;
import model.ViewPhotoModel;
import view.AbstractGUI;
import view.BuyPhotoOrSampleGUI;
import view.ViewPhotoGUI;
import view.ViewPhotoSampleGUI;
import client.CliMessage;
import client.MailMessage;


			
/**
 * This Class is a BuyPhotoController which extends AbstractController implements IValidateInput
 *
 * @author Tal
 */

public class BuyPhotoController extends AbstractController implements IValidateInput
{	
	       
	private	BuyPhotoOrSampleGUI buyPhotoView;
	private BuyPhotoOrSampleModel buyreqModel;
	private SearchPhotoModel photoDetails;
	private Observer perviousObserver;
	private UserPermissions up;
	private int serviceId;
    private boolean discount;  

	
	/**
	 * This is Buy PhotoController constructor.
	 * @param buyPhotoView is a Buy Photo Or Sample Window GUI instance.
	 * @param buyreqModel is a BuyPhotoOrSample Model instance.
	 */
	public BuyPhotoController( BuyPhotoOrSampleGUI buyPhotoView ,BuyPhotoOrSampleModel buyreqModel,SearchPhotoModel pDetails,Observer observer, AbstractGUI sResView,int service,boolean dis) 
	{
		super(sResView,buyreqModel);
		this.buyPhotoView = buyPhotoView;
		this.buyreqModel=buyreqModel;
		this.photoDetails=pDetails;
		this.perviousObserver=observer;
	    this.serviceId=service;
	    this.discount=dis;
		this.up = UserPermissions.getInstance(0, null, null);
		buyPhotoView.setVisible(true);	
		buyPhotoView.addBuyActionListener(new BuyListener(buyreqModel));
		
	
	}

	

	@Override
	public boolean validateInput() 
	{
		
			if(buyPhotoView.getCCNumber().equals("") || buyPhotoView.getCCV().equals(""))
			{
				
				buyPhotoView.displayWrnMessage("You MUST enter All Fields to Buy!!");
				
				return false;
			}
			
			if(!getDateValidation() )
			{
				buyPhotoView.displayWrnMessage("You Credit Card Date is Expired!!");
				
				return false;
			}
			
			if(buyPhotoView.getCreditTypeIndex()<1)
			{
				buyPhotoView.displayWrnMessage("You Have to Choose Credit Card Type!!");
					
					return false;
			}
			
			if(! getTextFieldValidation())	
				return false;
		
		return true;
		
	}
	
	/**
	 * checks date validation.
	 *
	 * @return the validate date
	 */
	public boolean getDateValidation()
	{
	
	  //CurrentDate
		Date date = new Date();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		
		String currTime= sd.format(date);
		System.out.println("curr Date:"+currTime);
	    Date currentDate=null;
		try {
			currentDate = sd.parse(currTime);
		} catch (ParseException e) {
			System.out.println("Current Date Problem Parse");
			e.printStackTrace();
		}
		
		//Date that from Spinners
		
	    String yourDateString =buyPhotoView.getDateFormtDB(); 
	    SimpleDateFormat yourDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	    Date yourDate=null;
		try {
			yourDate = yourDateFormat.parse(yourDateString);
		} catch (ParseException e) {
			 System.out.println("Your Date Problem Parse");
			e.printStackTrace();
		}
	    
		
		
		//checks validation
	    if (yourDate.after(currentDate) || yourDate.equals(currentDate)) 
	    {
	    	 System.out.println("correct date");
	    	 return true;
	           
	    }else{
	         System.out.println("Before");
	         return false;
	    }
				    
	}
	
	/**
	 * checks text field validation.
	 *
	 * @return the text field
	 */
	public boolean getTextFieldValidation()
	{
		
		String ccv=buyPhotoView.getCCV();
		String credit=buyPhotoView.getCCNumber();
		
		System.out.println("credit: "+credit.length()+"   ccv:"+ccv.length());
		
		//length checking
		if(ccv.length()>3)
		{
			buyPhotoView.displayWrnMessage("Your CCV number is too Long!!");
			 return false;
		}
		
		if (credit.length()>16)
		{
			buyPhotoView.displayWrnMessage("Your Credit card number is too Long!!");
			 return false;
		}
		
		if(ccv.length()<3)
		{
			buyPhotoView.displayWrnMessage("Your CCV number is too Short!!");
			 return false;
		}
		
		if (credit.length()<16)
		{
			buyPhotoView.displayWrnMessage("Your Credit card number is too Short!!");
			 return false;
		}
		
		
		//check ccv integer
		for(int i=0; i<ccv.length();i++)
		{
			if (ccv.charAt(i)<'0' || ccv.charAt(i)>'9')
			{
				buyPhotoView.displayWrnMessage("Your Must Enter Numbers in ccv!!!");
					return false;
			}
		}
		
		//check credit integer
		for(int i=0; i<credit.length();i++)
		{
			if (credit.charAt(i)<'0' || credit.charAt(i)>'9')
			{
				buyPhotoView.displayWrnMessage("Your Must Enter Numbers in credit card!!!");
					return false;
			}
		}
		
		return true;
	}
	
	/**
	 * This is SendMail method-send mail to customer for his Subscription 
	 * @param String body, String email
	 */
	
	public void SendMail(String body,String email)
	{
		MailMessage send = new MailMessage();
		
		
		send.sendMail(email,"Receipt From SGI Finance System ",body);
     }
	
	/**
	    * open View Photo according to user choice
	    * create new Objects GUI,Model,Controller
	    */
	  public void ViewPhoto()
	  {  
		///if the customer bought the photo - display it now
			
	        //set the view photo model with a photo to display
			ArrayList<SearchPhotoModel> photosToDispley = new ArrayList<SearchPhotoModel>();
			photosToDispley.add(photoDetails);
			SearchResultModel photos = new SearchResultModel(photosToDispley);
			ViewPhotoModel photoModel = new ViewPhotoModel(photos);
			
			//print the link to file (in console - for developer)
			String photoToDisplayFilePath = photoDetails.getLinkToFile();
			System.out.println("View Photo:"+photoToDisplayFilePath);
			
			//set the GUI and Controller of view photo
			ViewPhotoGUI photoView = new ViewPhotoGUI();
			
			ViewPhotoController viewPhotoCon = new ViewPhotoController(photoView,photoModel);
			
			buyPhotoView.dispose();
			//add observer to new controller and delete the rest							
			setCurrentObserver(viewPhotoCon);						
			
			//add a listener to "back" button in View Photo  window
		
			setBackListener(perviousObserver,photoView);
	  }

	  /**
	    * open View Photo Sample according to user choice
	    * create new Objects GUI,Model,Controller
	    */
	  public void ViewPhotoSample()
	   {
		   
			//print the link to file (in console - for developer)
			String photoToDisplayFilePath = photoDetails.getLinkToFile();
			System.out.println("View Photo Sample:"+photoToDisplayFilePath);
			
			//set the GUI and Controller of view photo
			ViewPhotoSampleGUI photoSampleView = new ViewPhotoSampleGUI();
			
			ViewPhotoSampleController viewPhotoSampleCon = new ViewPhotoSampleController(photoSampleView,photoDetails);
			
			buyPhotoView.dispose();
			//add observer to new controller and delete the rest
			setCurrentObserver(viewPhotoSampleCon);						
			
			//add a listener to "back" button in View Photo Sample  window
			setBackListener(perviousObserver,photoSampleView);
	   }

	/**
	 * Inner class that handles when Buy Button Pressed , implements ActionListener.
	 *
	 * @author Tal
	 */
	
	class BuyListener implements ActionListener
	{
		
		private BuyPhotoOrSampleModel buyreqModel;
		
	
		public BuyListener(BuyPhotoOrSampleModel buyreqModel)
		{
		
			this.buyreqModel=buyreqModel;
		
		}
		
	
		@Override
		public void actionPerformed(ActionEvent arg0) 
		{
			
			if(!validateInput())
				return;
	       
			buyPhotoView.displayWrnMessage("");
			//init subreqModel
			buyreqModel.setCreditN(buyPhotoView.getCCNumber());
			buyreqModel.setCCV(Integer.parseInt(buyPhotoView.getCCV()));
			buyreqModel.setExpire(buyPhotoView.getDateFormtDB());
			buyreqModel.setType(buyPhotoView.getCreditType());
			
	
			int uid = up.getCurrUserID();
			String creditN = buyPhotoView.getCCNumber();
			String ccv = buyPhotoView.getCCV();
			String type=buyPhotoView.getCreditType();
			
			//validate credit card and ccv from db
			String sql = "search" + "SELECT * " 
		                          + " FROM payment_method AS p , cus_payment_method AS c" 
		                          + " WHERE c.pid = p.pid"
		                          + " AND p.creditnum = '" + creditN + "'" 
			                      +	" AND c.uid = "+ uid
			                      + " AND p.ccv <> '" + ccv + "'" 
			                      + " UNION"
			                      + " SELECT * " 
		                          + " FROM payment_method AS p , cus_payment_method AS c" 
			                      + " WHERE c.pid = p.pid"
			                      + " AND p.creditnum = '" + creditN + "'" 
			                      +	" AND c.uid <> "+uid+" ";
					 
		// Send a query to DB
			sendToServer(sql);
	     
		}
}



	
	
	@Override
	public void handleDBRequestSuccess()
	{
		//
		
	}


	
	@Override
	public void handleDBSearchResult(CliMessage dbResult) 
	{	
		//get Details tupple
		ArrayList<HashMap<String, String>> srs = dbResult.getSrs();
		
		 
		//invoice check up
	  if(srs.get(0).get("INVOICE_NUMBER")==null)
	  {
			   buyPhotoView.displayWrnMessage("Invalid credit details. please check your card!");
			   buyPhotoView.clearFields();
	  }
	  else
	  {
		   //back from finance System
			int uid=up.getCurrUserID();
			int invoice=Integer.parseInt(srs.get(0).get("INVOICE_NUMBER"));		
							
			   //insert to customer_orders
			String insertQuery = "adu"	+"INSERT INTO customer_orders "
	             	                    +"(uid,invoice_number) VALUES "
	                                 	+"(" + uid + "," + invoice + ")";
		  
		  
			// Send a query to DB
			sendToServer(insertQuery);
			
			//send mail finance System+joptionPane
	
	        //send mail from finance System + jOptionPane
			  JOptionPane.showMessageDialog(null, "Finance System successfully Has Charged Customer " ,"Finace System Notification", JOptionPane.INFORMATION_MESSAGE);
			String mail=srs.get(0).get("EMAIL");
			String FName=srs.get(0).get("FNAME");
			String LNAME=srs.get(0).get("LNAME"); 
			String Price=srs.get(0).get("PRICE_PAID");
			String Date=srs.get(0).get("TIMESTAMP");
			String Credit=srs.get(0).get("CREDITNUM");
			int service=Integer.parseInt(srs.get(0).get("SERVICE_ID"));
			
			String serviceName;
			if (service==1)
				serviceName="Buy Photo";
			else
				serviceName="Buy Sample";
			
			String newCredit=Credit.substring(0,4)+"-"+"XXXX"+"-"+"XXXX"+"-"+Credit.substring(11,15);
			String NewDate=Date.substring(0,Date.length()-5);
			String body=" Dear "+LNAME+" "+FName+","
					+"\n Your Invoice Number : "+ ""+invoice
					+"\nDescription : "+ serviceName 
					+ "\nCredit Details : "+newCredit+"\n Price :"+ Price+"$" 
					+"\n Date : "+NewDate;
			//send Mail
			SendMail(body,mail);
			
			/////view photo
			
			//insert to customer photo
			
			int location=photoDetails.getLocation();
			String timestamp=photoDetails.getTimeStamp();		
		
			
	        //View photo         
	        if (service==1)
	        {
	        	System.out.println("show photo");
	        	String insertQuery2 = "adu"	+"INSERT INTO customer_photos "
                        +"(uid,location,timestamp) VALUES "
 	                   +"(" + uid + "," + location + ",'"+ timestamp +"'"+")";


                        // Send a query to DB
                           sendToServer(insertQuery2);
	        	ViewPhoto();
	        }
	        else//sample
	        {
	        	System.out.println("show Sample");
	        	String insertQuery3 = "adu"	+"INSERT INTO customer_samples "
                        +"(uid,locationsample,timestampsample) VALUES "
 	                   +"(" + uid + "," + location + ",'"+ timestamp +"'"+")";


                   // Send a query to DB
                 sendToServer(insertQuery3);
	        	ViewPhotoSample();
	        }
			
  		}
	}
	 
	  

	@Override
	public void handleNullSearchResult() 
	{
		///charge customer
		///Finance System
		///Finance System Controller
		 
		int uid=up.getCurrUserID();
		//create finance System Model
		FinanceSystemModel finSystemModel=new FinanceSystemModel();
		//init model
		finSystemModel.setUID(uid);
		//buy or Sample photo - service Id-1-photo,3-sample
		finSystemModel.setGID(serviceId);
		finSystemModel.setCreditN(buyreqModel.getCreditN());
		finSystemModel.setCCV(buyreqModel.getCCV());
		finSystemModel.setExpire(buyreqModel.getExpire());
		finSystemModel.setType(buyreqModel.getType());
		finSystemModel.setDiscount(discount);
		
		//create controller
		FinanceSystemController finSysCon=new FinanceSystemController(finSystemModel,this);
		//set Observer
		setCurrentObserver(finSysCon);
	}


}
